package com.lmc.chatroom.service;

import com.lmc.chatroom.mapper.friendMapper;
import com.lmc.chatroom.mapper.messageMapper;
import com.lmc.chatroom.mapper.sessionMapper;
import com.lmc.chatroom.mapper.userMapper;
import com.lmc.chatroom.model.Friend;
import com.lmc.chatroom.model.MessageSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class sessionService {
    @Autowired
    private sessionMapper sessionMapper;
    @Autowired
    private friendMapper friendMapper;
    @Autowired
    private messageMapper messageMapper;

    public List<MessageSession> selectSessionsByUserId(Integer userId) {
        log.info("selectSessionsByUserId");
        List<MessageSession> sessionList = new ArrayList<>();
        List<Integer> sessionIds =  sessionMapper.selectSessionIdByUserId(userId);
        for (int i = 0 ; i < sessionIds.size(); i++) {
            MessageSession session = new MessageSession();
            session.setSessionId(sessionIds.get(i));
            session.setFriend(selectFriendsByUserId(sessionIds.get(i), userId));
            String lastMessage = messageMapper.getLastMessage(sessionIds.get(i));
            if(lastMessage != null) {
                session.setLastMessage(lastMessage);
            }else{
                session.setLastMessage("");
            }
            sessionList.add(session);
        }
        log.info("sessionIds"+sessionIds.toString());
        log.info("sessionList"+sessionList.toString());
        return sessionList;
    }

    public Friend selectFriendsByUserId(Integer sessionId, Integer userId) {
        Integer friendId = sessionMapper.selectFriendIdBySessionId(sessionId,userId);

        log.info(friendId.toString());
        return friendMapper.getFriend(friendId);

    }

    @Transactional
    public Integer creatSession(Integer friendId,Integer userId) {
        MessageSession session = new MessageSession();
        Integer sessionId = sessionMapper.createSessionId(session);
//        log.info("新建会话的sessionId"+sessionId.toString());
        Integer result = sessionMapper.createSession(session.getSessionId(),userId,friendId);
        log.info("新建会话的result"+result.toString());
        return session.getSessionId();
    }

}
